# -*- coding: utf-8 -*-
import requests
import time
import json
import random
from dao import SQLiteDb

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0'}
cookies = {'sessionid': '{已登录sessionid}'}

glodata = {}
filters = ''

dao = SQLiteDb('./Dyin.db')


def followers(sec_user_id):
    # 粉丝数
    follo = 0
    url = "https://www.iesdouyin.com/web/api/v2/user/info/?sec_uid=%s" % sec_user_id
    res = requests.get(url, headers=headers, cookies=cookies).json()
    if res['status_code'] == 0:
        follo = res['user_info']['follower_count']
    return follo

def publicity(sec_user_id):
    # 最近直播
    bingo = False
    tm  = int(time.time())
    url = "https://aweme.snssdk.com/aweme/v2/shop/live/publicity/?size=8&sec_user_id=%s&page=1&is_vcd=1&request_tag_from=h5&os_api=23&device_type=MI+5s&ssmix=a&manifest_version_code=150601&dpi=270&uuid=510000000093636&app_name=aweme&version_name=15.6.0&ts=%s&cpu_support64=false&app_type=normal&appTheme=dark&ac=wifi&host_abi=armeabi-v7a&update_version_code=15609900&channel=update&device_platform=android&iid=756911375662439&version_code=150600&openudid=a35345479791d833&device_id=510603072122237&resolution=810*1440&os_version=6.0.1&language=zh&device_brand=Xiaomi&aid=1128&minor_status=0&mcc_mnc=46005" % (sec_user_id, str(tm))
    payload = {}
    headers = {
      'Cookie': '{已登录sessionid}'
    }
    res = requests.request('GET', url, headers=headers, data=payload).json()
    if res['status_code'] == 0:
        if len(res['live_record']) > 0:
            record_last_time = int(res['live_record'][0]['date_time'])
            # 近30天未直播
            if (int(time.time()) - record_last_time) < (86400 * 30):
                bingo = True
    if bingo:
        print('-'*50)
    else:
        print('+'*50)
    return bingo


def shopdetail(sec_author_id, user_id, nick_name):
    # 店铺详情
    url = '''https://aweme.snssdk.com/aweme/v2/shop/user/reputation/detail/?request_tag_from=rn
    &sec_author_id={0}&os_api=23&device_type=MI+5s&ssmix=a&manifest_version_code=150601
    &dpi=270&uuid=510000000093636&app_name=aweme&version_name=15.6.0&ts={1}&cpu_support64=false&app_type=normal&appTheme=dark&ac=wifi
    &host_abi=armeabi-v7a&update_version_code=15609900&channel=update&_rticket=1619174046212&device_platform=android&iid=756911375662439
    &version_code=150600&cdid=d271d8c9-7510-4b0d-9272-720a3c59885a&openudid=a35345479791d833&device_id=510603072122237&resolution=810*1440
    &os_version=6.0.1&language=zh&device_brand=Xiaomi&aid=1128&minor_status=0&mcc_mnc=46005'''.format(sec_author_id, int(time.time()))
    res = requests.get(url, headers=headers, cookies=cookies).json()
    if res['status_code'] == 0:
        sales = res['sales']
        bingo = publicity(sec_author_id)
        lives = '有直播' if bingo else '无直播'
        views = 'https://haohuo.jinritemai.com/views/shop/index?id=%s' % res['encrypt_shop_id']
        fans  = followers(sec_author_id)
        tmstr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        print(tmstr, nick_name, sales, lives)
        # 保存到数据库
        # dao.addUsers(user_id, sec_author_id, nick_name, sales, views, lives, fans, tmstr)
        # 保存到文件
        #with open('./record.txt', 'a+', encoding='utf-8') as f:
        #    f.write(nick_name +'\t'+ sales +'\t'+ lives + '\t' + fans + '\t' + views + '\t' + tmstr + '\n')
        glodata[sec_author_id] = 1
    else:
        print(res)


def favorite(cursor, page_num):
    global filters
    ts = int(time.time())
    url = '''https://aweme.snssdk.com/aweme/v2/commerce/favorite/feed?cursor={0}&request_tag_from=lynx&filters={1}
    &feedbacks&page_num={2}&page_name=order_homepage&b_type_new=2&os_api=23&device_type=MI+5s&ssmix=a&manifest_version_code=150601
    &dpi=270&uuid=510000000093636&app_name=aweme&version_name=15.6.0&ts={3}&cpu_support64=false&app_type=normal&appTheme=dark&ac=wifi
    &host_abi=armeabi-v7a&update_version_code=15609900&channel=update&_rticket=1619174652176&device_platform=android&iid=756911375662439
    &version_code=150600&cdid=d271d8c9-7510-4b0d-9272-720a3c59885a&openudid=a35345479791d833&device_id=510603072122237&resolution=810*1440
    &os_version=6.0.1&language=zh&device_brand=Xiaomi&aid=1128&minor_status=0&mcc_mnc=46005'''.format(cursor, filters, page_num, ts)
    res = requests.get(url, headers=headers).json()
    if res['status_code'] == 0:
        for item in res['item_cards']:
            if 'user' in item:
                print(item['user']['nickname'])
                print(item['product']['title'])

            # type = 1 直播 , type = 2 非直播
            
            if item['type'] == 1:
                filters += ('%2C1_' + item['live']['room_id'])

            if item['type'] == 2:
                filters += ('%2C2_' + item['product']['product_id'])
                try:
                    user_id    = item['user']['id']
                    user_name  = item['user']['nickname']
                    sec_kol_id = item['product']['sec_kol_id']
                    if sec_kol_id in glodata:
                        print('|---同一店铺商品')
                    else:
                        shopdetail(sec_kol_id, user_id, user_name)
                except Exception as e:
                    pass
            
            if item['type'] == 3:
                filters += ('%2C3_' + item['activity']['activity_id'])

            time.sleep(1)
    else:
        print(res)

def main():
    global filters
    filters = ''
    cursor = 0
    page_num = 1
    for i in range(1, 60):
        print(cursor, page_num)
        try:
            # 适当跳页
            if (i % 5) < 2:
                favorite(cursor, page_num)
        except Exception as e:
            pass
        if cursor == 0:
            cursor += 2
        cursor += 10
        page_num += 1
        #todo: 随机休息
        time.sleep(random.randint(3,15))


if __name__ == '__main__':

    while True:
        main()
        time.sleep(152)
